package com.eagle.security.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.eagle.security.dao.PermissionDao;
import com.eagle.security.entries.Permission;

@Repository
public class PermissionDaoImpl implements PermissionDao {

    @Resource
    private JdbcTemplate template;
    
    @Override
    public List<Permission> findPermissionsByCond(Permission mo, int start, int pageSize){
        StringBuffer sql = new StringBuffer("select * from permission ");
        Object[] args = gernateWhereCond(sql, mo, start, pageSize);
        return template.query(sql.toString(), permissionMapper, args );
    }
    
    private final RowMapper<Permission> permissionMapper = new RowMapper<Permission>() {
        @Override
        public Permission mapRow(ResultSet rs, int arg1) throws SQLException {
            Permission mo = new Permission();
            mo.setId( rs.getInt("id") );
            mo.setUuid( rs.getString("uuid") );
            mo.setParent_uuid( rs.getString("parent_uuid") );
            mo.setKey( rs.getString("key") );
            mo.setName( rs.getString("name") );
            return mo;
        }
    };
    
    private Object[] gernateWhereCond(StringBuffer b, Permission mo, int start, int pageSize) {
        List<Object> l = new ArrayList<Object>();
        b.append(" WHERE 1=1 ");
        if (mo != null) {
            if ( StringUtils.isNotBlank(mo.getParent_uuid())) {
                b.append(" AND ").append(" parent_uuid = ? ");
                l.add(mo.getParent_uuid());
            }else{
                b.append(" AND ").append(" parent_uuid = ? ");
                l.add( "" );
            }
        }
        b.append(" ORDER BY ").append(" sort ASC ");
        if (start < 0 || pageSize < 0) {

        }
        else {
            b.append(" limit ?,?");
            l.add(start);
            l.add(pageSize);
        }
        return l.toArray(new Object[l.size()]);
    }
}
